package com.zretc.controller;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.zretc.service.StatisticsService;
import com.zretc.service.impl.StatisticsServiceImpl;

/**
 * Servlet implementation class StatisticsServlet
 */
@WebServlet("/StatisticsServlet")
public class StatisticsServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private StatisticsService statisticsService = new StatisticsServiceImpl();
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public StatisticsServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String op = request.getParameter("op");
		
		// 判断
		if(op == null || "getEveryRegionTotalIncome".equals(op)) {
			// 当条件为空或者getEveryRegionTotalIncome---获取每个城市的总收入
			doGetEveryRegionTotalIncome(request, response);
		} else if("getEveryStyleTotalIncome".equals(op)) {
			//当判断条件为getEveryStyleTotalIncome--获取每个风格民宿的总收入
			doGetEveryStyleTotalIncome(request,response);
		}
	}

	private void doGetEveryStyleTotalIncome(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 调用模型层,获取数据
		List<Map<String, Object>> everyStyleTotalIncome = statisticsService.getEveryStyleTotalIncome();
		
		// 利用第三方工具生成JSON
		Gson gson = new Gson();
		// 下面的是集合 ,toJson() 序列化,将数组或集合转换成JSON字符串
		String jsonObject = gson.toJson(everyStyleTotalIncome);

		// 设置响应的内容类型,设置下面的才是对象。
		response.setContentType("application/json;charset=utf-8");
		response.getWriter().write(jsonObject);
		
	}

	private void doGetEveryRegionTotalIncome(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 调用模型层,获取数据
		List<Map<String, Object>> everyRegionTotalIncome = statisticsService.getEveryRegionTotalIncome();
		
		// 利用第三方工具生成JSON
		Gson gson = new Gson();
		// 下面的是集合 ,toJson() 序列化,将数组或集合转换成JSON字符串
		String jsonObject = gson.toJson(everyRegionTotalIncome);

		// 设置响应的内容类型,设置下面的才是对象。
		response.setContentType("application/json;charset=utf-8");
		response.getWriter().write(jsonObject);
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
